package com.fun.demo.fun;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class JavaDyCompiler {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, MalformedURLException, InvocationTargetException, NoSuchMethodException {
        //获得系统的java编译器
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        //编译文件，编译成功返回 0 否则 返回 1
        int flag = compiler.run(null, null, null,"D:/Hello1.java");
        System.out.println(flag == 0 ? "编译成功" : "编译失败");

        //指定class路径，默认和源代码路径一致，加载class
        URLClassLoader classLoader = new URLClassLoader(new URL[]{new URL("file:/d:/")});
        Object o = classLoader.loadClass("Hello1").newInstance();
        Method m = o.getClass().getMethod("fun1");
        m.invoke(o,new Object[]{});


    }
}
